import React, { useState } from 'react';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';
import '../assets/styles/RegisterStyles.css';

const Register = () => {
  const [username, setUsername] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [walletAddress, setWalletAddress] = useState('');
  const [privateKey, setPrivateKey] = useState(''); // 保存私钥
  const [mnemonic, setMnemonic] = useState(''); // 保存助记词
  const [errorMessage, setErrorMessage] = useState('');
  const history = useNavigate();

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      const response = await axios.post('http://localhost:5000/api/auth/register', { username, email, password });
      console.log('Response Data:', response.data);  // 添加日志
      // 设置钱包地址和私钥
      setWalletAddress(response.data.wallet_address);
      setPrivateKey(response.data.privateKey); // 获取私钥
      setMnemonic(response.data.mnemonic); // 获取助记词
      
      // 提示用户注册成功并展示钱包地址和私钥
      alert(`注册成功！\n钱包地址: ${response.data.wallet_address}\n私钥: ${response.data.privateKey}\n助记词: ${response.data.mnemonic}\n请妥善保存您的私钥，因为无法再次查看！`);

      // 自动生成下载链接
      const element = document.createElement("a");
      const fileContent = `Your private key:\n${response.data.privateKey}\n\nYour mnemonic:\n${response.data.mnemonic}`;
     const file = new Blob([fileContent], { type: 'text/plain' });
      element.href = URL.createObjectURL(file);
      element.download = `${response.data.wallet_address}_privateKey.txt`;
      document.body.appendChild(element); // 让链接可以在所有浏览器中正常使用
      element.click();

      // 注册成功后跳转到登录页
      history('/login');
    } catch (error) {
      console.error('注册失败:', error.response?.data || error.message);
      setErrorMessage(error.response?.data?.message || '注册失败');
    }
  };

  return (
    <div className="register-container">
      <div className="register-card">
        <h2 className="register-title">注册</h2>
        <form onSubmit={handleSubmit}>
          <div className="register-form-group">
            <label htmlFor="username">用户名:</label>
            <input 
              type="text" 
              id="username" 
              className="register-input" 
              value={username} 
              onChange={(e) => setUsername(e.target.value)} 
              required 
            />
          </div>
          <div className="register-form-group">
            <label htmlFor="email">邮箱:</label>
            <input 
              type="email" 
              id="email" 
              className="register-input" 
              value={email} 
              onChange={(e) => setEmail(e.target.value)} 
              required 
            />
          </div>
          <div className="register-form-group">
            <label htmlFor="password">密码:</label>
            <input 
              type="password" 
              id="password" 
              className="register-input" 
              value={password} 
              onChange={(e) => setPassword(e.target.value)} 
              required 
            />
          </div>
          <button type="submit" className="register-button">注册</button>
          <p>
            已有账号？<a href="/login" className="register-link">登录</a>
          </p>
        </form>
        {errorMessage && <p className="register-error">{errorMessage}</p>}
        
        {/* 注册成功后展示钱包地址和提示 */}
        {walletAddress && (
          <div className="register-success">
            <p>注册成功！</p>
            <p>钱包地址: {walletAddress}</p>
            <p>请妥善保管您的私钥。下载后请务必保存好，避免泄露。</p>
          </div>
        )}
      </div>
    </div>
  );
};

export default Register;
